package com.situ.shoplookweb.controller;

import com.situ.shoplook.common.model.Order;
import com.situ.shoplook.common.model.ShoppingCart;
import com.situ.shoplook.common.model.User;
import com.situ.shoplook.common.service.OrderService;
import com.situ.shoplookweb.service.ShoppingCartService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

/**
 * @Author xinchen
 * @Date: 2024/09/06/ 14:27
 * @Description
 */
@Controller
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 订单详情
     * @return
     */
    @GetMapping("/order/{orderNo}")
    public String orderPage(HttpServletRequest request, @PathVariable("orderNo") String orderNo, HttpSession session){
        User user = (User) session.getAttribute("newBeeMallUser");
        Order order = orderService.selectByOrderNo(orderNo, user.getUserId());
        request.setAttribute("orderDetailVO",order);
        return "mall/order-detail";
    }

    /**
     * 我的订单
     */
    @GetMapping("/orders")
    public String ordersPage(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpSession session){
        User user = (User) session.getAttribute("newBeeMallUser");
        params.put("userId", user.getUserId());
        if (ObjectUtils.isEmpty(params.get("page"))) {
            params.put("page", 1);
        }
        params.put("limit", 5);
        //封装我的订单数据
        request.setAttribute("orderPageResult", orderService.searchByPage(
                Integer.parseInt(params.get("page").toString()),
                Integer.parseInt(params.get("limit").toString()),
                new Order()));
        request.setAttribute("path", "orders");
        return "mall/my-orders";
    }

    /**
     * 提交订单
     */
    @GetMapping("/saveOrder")
    public String saveOrder(HttpSession session){
        User user = (User) session.getAttribute("newBeeMallUser");
        List<ShoppingCart> myshopCart = shoppingCartService.getMyShoppingCartItems(user.getUserId());
        //判断地址
        if(!StringUtils.isEmpty(user.getAddress().trim())){
            //无收获地址
            throw new IllegalStateException("请先添加收获地址");
        }
        if(ObjectUtils.isEmpty(myshopCart)){
            throw new IllegalStateException("购物车为空");
        }
        //保存订单并返回订单号
        String saveOrderResult = orderService.saveOrder(user, myshopCart);
        return "redirect:/order/" + saveOrderResult;
    }
}
